<template>
  <div>
    <el-form :inline="true" :model="categoryIdList" class="demo-form-inline">
      <el-form-item label="一级分类">
        <el-select v-model="categoryIdList.category1Id" placeholder="请选择" :disabled="showSelect">
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="c1 in category1List"
            :key="c1.id"
            @click.native="getCategory2List(c1.id)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="categoryIdList.category2Id" placeholder="请选择" :disabled="showSelect">
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="c2 in category2List"
            :key="c2.id"
            @click.native="getCategory3List(c2.id)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="categoryIdList.category3Id" placeholder="请选择" :disabled="showSelect">
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="c3 in category3List"
            :key="c3.id"
            @click.native="$emit('getCategoryId', categoryIdList)"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "CategorySelect",
  // 判断选择分类的选择框是否要禁用
  props: ['showSelect'],
  data() {
    return {
      // 存储分类的id
      categoryIdList: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      // 存放一级分类数据
      category1List: [],
      // 存储二级分类数据
      category2List: [],
      // 存储三级分类数据
      category3List: [],
    };
  },
  methods: {
    // 获取一级分类的数据
    async getCategory1List() {
      const result = await this.$API.attr.reqCategory1List();
      if (result.code === 200) {
        this.category1List = result.data;
      }
    },
    // 当一级分类选择完毕后，执行获取二级分类数据的函数
    async getCategory2List(id) {
      // 一级分类的选择发生改变时，都要清空二级跟三级分类选择的数据
      this.categoryIdList.category2Id = "";
      this.categoryIdList.category3Id = "";
      const result = await this.$API.attr.reqCategory2List(id);
      if (result.code === 200) {
        this.category2List = result.data;
      }
      this.$emit('getCategoryId', this.categoryIdList)
    },
    // 当一级分类和二级分类选择完毕后，执行获取三级分类数的函数
    async getCategory3List(id) {
      // 二级分类的选择发生改变时，都要清空三级分类选择的数据
      this.categoryIdList.category3Id = "";
      const result = await this.$API.attr.reqCategory3List(id);
      if (result.code === 200) {
        this.category3List = result.data;
      }
      this.$emit('getCategoryId', this.categoryIdList)
    },
  },
  mounted() {
    // 页面挂载完毕就调用获取一级分类数据的函数
    this.getCategory1List();
  },
};
</script>

<style>
</style>